package transport.service;

import action.Dispatcher;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import queue.TaskQueue;
import transport.protocol.MessageHolder;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;

public class SimpleChatService extends AbstractChatService {

    private ApplicationContext ctx;

    private Dispatcher dispatcher;

    private static Logger logger = Logger.getLogger(SimpleChatService.class);

    public static AtomicBoolean shutdown = new AtomicBoolean(false);

    private BlockingQueue<MessageHolder> taskQueue;

    private ExecutorService takeExecutor;

    private ExecutorService taskExecutor;

    private int queueSize = 10;

    public SimpleChatService() {}

    public SimpleChatService(int queueSize) {
        this.queueSize = queueSize;
    }

    public void init() {
        ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        dispatcher = (Dispatcher) ctx.getBean("dispatcher");

        takeExecutor = Executors.newSingleThreadExecutor();
        taskExecutor = Executors.newFixedThreadPool(queueSize);
        taskQueue = TaskQueue.getQueue();
        logger.info("chat后台服务初始化完成");
        logger.info("任务执行队列size:" + queueSize);
    }

    public void start() {
        takeExecutor.execute(new Runnable() {

            public void run() {
                while (!shutdown.get()) {
                    try {
                        MessageHolder messageHolder = taskQueue.take();
                        logger.info("TaskQueue取出任务: taskQueue=" + taskQueue.size());
                        startTask(messageHolder);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        logger.error(e);
                        logger.warn("receiveQueue task ", e);
                    }
                }
            }

            private void startTask(final MessageHolder holder) {
                taskExecutor.execute(new Runnable() {
                    public void run() {
                        logger.info("开始执行取出的任务 messageHolder=" + holder);
                        dispatcher.dispatch(holder);
                    }
                });
            }
        });

        logger.info("chat后台服务启动完成");
    }
}
